/**
 * ajax 封装 axios 模块
 * 返回一个 Promise 对象
 */
import axios from 'axios'
axios.defaults.withCredentials=true
const options = {
  // headers: {
  //   'Access-Control-Allow-Origin': '121.5.18.13:8080'
  // }
}
export default function ajax(url, data={}, type='GET') {
  // data 即可以是 GET 请求的 query 参数，也可以是 POST 请求的 data 参数
  return new Promise((resolve, reject) => {
    let promise
    if (type === 'GET') {
      let dataStr = ''
      Object.keys(data).forEach(key => {
        dataStr += `${key}=${data[key]}&`
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url =  url + '?' + dataStr
      }
      promise = axios.get(url, options)
    } else if (type === 'POST') {
      promise = axios.post(url, data, options)
    } else if (type === 'DELETE') {
      promise = axios.delete(url, data, options)
    } else {
      console.log('ajax 无此请求')
    }

    promise
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}